package com.mangowang.module.main.ui;
import android.Manifest;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.havi.helper.ChatHelper;
import com.google.android.material.tabs.TabLayout;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mangowang.lib.common.App;
import com.mangowang.lib.common.base.BaseActivity;
import com.mangowang.lib.common.bean.UserBean;
import com.mangowang.lib.common.help.PermissionHelper;
import com.mangowang.lib.common.help.UserHelper;
import com.mangowang.lib.common.net.Apis;
import com.mangowang.lib.common.net.NetworkManager;
import com.mangowang.lib.common.net.WebApis;
import com.mangowang.lib.common.net.interfaces.OnRequestCallBack;
import com.mangowang.lib.common.proto.Index;
import com.mangowang.lib.common.util.APKVersionCodeUtils;
import com.mangowang.lib.common.util.StatusBarUtil;
import com.mangowang.lib.common.util.updateutil.UpdateManager;
import com.mangowang.lib.common.view.NoScrollViewPager;
import com.mangowang.module.main.other.HyphenateLibraryCallBackHandle;
import com.mangowang.module.main.web.ui.WebViewFragment;
import com.mangowang.module.main.R;
import com.mangowang.module.main.R2;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;

@Route(path = "/main/MainActivity")
public class MainActivity extends BaseActivity {

    @BindView(R2.id.viewPagers)
    NoScrollViewPager viewPager;
    @BindView(R2.id.tab_layout)
    TabLayout tabLayout;


    private long mExitTime;
    public String tureeName = "";
    private HomeFragment home;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#FFFFFF"), true);
        ButterKnife.bind(this);
        ChatHelper.getInstance().setHyphenateLibraryCallBack(new HyphenateLibraryCallBackHandle());
        App.addTempActivity(this);
        initMenus();
        initView();
        LoadVersion();
        getPermission();
    }




    String[] tabNames;
    int[] tabIcons;

    private void initMenus() {
        tabNames = getResources().getStringArray(R.array.main_tabs);
        TypedArray ar = getResources().obtainTypedArray(R.array.main_tab_icons);
        int len = ar.length();
        tabIcons = new int[len];
        for (int i = 0; i < len; i++) {
            tabIcons[i] = ar.getResourceId(i, 0);
        }
        ar.recycle();
    }

    private void initView() {
        tureeName = getIntent().getStringExtra("trueName");
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(home = new HomeFragment());
        fragments.add(WebViewFragment.newInstance(App.getServiceHost() + WebApis.statistics));
        fragments.add(WebViewFragment.newInstance(App.getServiceHost()+WebApis.businessSchool));
        fragments.add(new MineFragment());
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return null;
            }

        });
        //设置图标
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabNames.length; i++) {
            tabLayout.getTabAt(i).setCustomView(getTabView(tabNames[i], tabIcons[i]));
        }

        // 设置监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    home.onResume();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


    }

    public View getTabView(String tabName, int tabIcon) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.tab_layout, null);
        ImageView iv_tab = view.findViewById(R.id.iv_tab);
        TextView tv_tab = view.findViewById(R.id.tv_tab);
        iv_tab.setImageResource(tabIcon);
        tv_tab.setText(tabName);
        return view;
    }

    //返回
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
//                MainApplication.finishAllActivity();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void LoadVersion() {
        Index.get_app_version_info.Builder builder = Index.get_app_version_info.newBuilder();
        builder.setClient("android");
        NetworkManager.INSTANCE.post(Apis.versionCode, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
                checkVersion(response);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
            }
        });

    }

    private void checkVersion(byte[] response) {
        String versionName = APKVersionCodeUtils.getVerName(mContext);
        Index.get_app_version_info versionBean = null;
        try {
            versionBean = Index.get_app_version_info.parseFrom(response);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        Log.e("mango", "checkVerison: " + versionBean);
        // 改为匹配版本号
        float serviceVersion = Float.parseFloat(versionBean.getVersion());
        float locationeVersion = Float.parseFloat(versionName);
        if (locationeVersion < serviceVersion) {
            UpdateManager.getInstance()
                    .setContext(this)
                    .setFragmentManager(getSupportFragmentManager())
                    .setUrl(versionBean.getDownloadUrl())
                    .setIsforce(versionBean.getForce())
                    .setContent(versionBean.getContext())
                    .start();
        }
    }

    private void getPermission()
    {

        List<String> permission = new ArrayList<>();
        permission.add(Manifest.permission.CAMERA);
        permission.add(Manifest.permission.INTERNET);
        PermissionHelper.getInstance().getPermissionGroup((BaseActivity)mContext, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFail() {
                Toast.makeText(mContext, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, permission);
    }



}
